package config

import (
	"fmt"
	"gostore/util/log"
	"io/ioutil"

	"gopkg.in/yaml.v3"
)

type Config struct {
	Profile struct {
		Active string
	}
	Server struct {
		Port  string
		Debug bool
	}
	Database DBConfig
}

type DBConfig struct {
	Type     string
	Host     string
	Port     string
	Username string
	Password string
	DBName   string
}

func ReadYamlWithPath(path string) (conf *Config, err error) {
	l := log.Factory(ReadYamlWithPath)
	l.Info("reading config ", path)

	file, err := ioutil.ReadFile(path)
	if err != nil {
		l.Info("read '", path, "' fail", err)
		return nil, err
	}

	conf = &Config{}

	err = yaml.Unmarshal([]byte(file), conf)

	if err != nil {
		l.Fatal("yaml parse fail")
	}

	return
}

var defaultYamlPath = "./app.yml"

func ReadYaml() (conf *Config, err error) {
	conf, err = ReadYamlWithPath(defaultYamlPath)
	if err == nil {
		active := conf.Profile.Active
		if len(active) > 0 {
			// 不同环境配置文件
			path := fmt.Sprintf("app-%s.yml", active)
			conf, err = ReadYamlWithPath(path)

		}
	}
	return
}

var Cfg *Config

func Init(cfg *Config) {
	Cfg = cfg
}
